package com.yanqu.road.server.cmd.wingroom;

import com.yanqu.road.message.YanQuMessage;
import com.yanqu.road.pb.wingroom.WingRoomProto;
import com.yanqu.road.server.GameServer;
import com.yanqu.road.server.command.Cmd;
import com.yanqu.road.server.command.Command;
import com.yanqu.road.server.gameplayer.GamePlayer;
import com.yanqu.road.server.gameplayer.module.wingroom.WingRoomModule;
import com.yanqu.road.server.manger.player.GamePlayerMgr;
import com.yanqu.road.server.manger.wingroom.WingRoomMgr;
import com.yanqu.road.server.protocol.Protocol;
import com.yanqu.road.utils.YanQuMessageUtils;
import io.netty.channel.ChannelHandlerContext;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

@Cmd(code = Protocol.S_WING_ROOM_USER_EVENT_DATA_STATUS_SYNC_DONE, desc = "事件变更已同步到跨服")
public class EventDataSyncDoneCmdFromCross implements Command {

    @Override
    public void execute(ChannelHandlerContext ctx, YanQuMessage packet) throws Exception {

        WingRoomProto.UserWingRoomEventDataSyncDone syncDone = WingRoomProto.UserWingRoomEventDataSyncDone.parseFrom(packet.getBytes());

        //通知影响的玩家
        //亲友+盟友
        Map<Long, Set<Long>> friendMap = new HashMap<>();

        WingRoomMgr.getAllFriendMap(syncDone.getUserIdList(), friendMap);

        for (Map.Entry<Long, Set<Long>> entry : friendMap.entrySet()) {
            if(entry.getKey() == GameServer.getInstance().getServerId()){
                //通知本服玩家，重新计算红点
                for (Long userId : entry.getValue()) {
                    GamePlayer player = GamePlayerMgr.getOnlinePlayer(userId);
                    if(player == null){
                        continue;
                    }
                    WingRoomMgr.getLogger().debug("-----------玩家计算事件红点：{}", player.getUserId());
                    player.getModule(WingRoomModule.class).calVisitRedDot(WingRoomProto.UserWingRoomRedDotSync.newBuilder());
                }

            }else {
                //通知其他区分玩家，重新计算红点
                WingRoomProto.CrossCalEventRedDotNotifyMsg.Builder crossReq = WingRoomProto.CrossCalEventRedDotNotifyMsg.newBuilder();
                crossReq.setServerId(entry.getKey());
                crossReq.addAllUserId(entry.getValue());
                GamePlayerMgr.sendPacket(0, YanQuMessageUtils.buildMessage(Protocol.C_WING_ROOM_CROSS_CAL_EVENT_RED_DOT_NOTIFY, crossReq));
            }
        }

    }


}
